package com.guoqing.example.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author ZhangGuoQing
 * @Date 2020/8/21/0021 16:49
 */
@RestController
public class LoginController {


    @RequestMapping("/login222")
    public String login(String username, String password) {
        return "haha";
    }

    @RequestMapping("/loginSuccess")
    public String loginSuccess() {
        //提示具体用户名称登录成功
        return getUsername() + " 登录成功";
    }

    //获取当前用户信息
    private String getUsername() {
        String username = null;
        //当前认证通过的用户身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //用户身份
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            username = "匿名";
        }
        if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }

    @RequestMapping("/r/menu10")
    public String menu() {
        return getUsername() + "访问 menu10";
    }

    @RequestMapping("/r/menu1")
    @PreAuthorize("hasAuthority('menu1')")
    public String menu1() {
        return getUsername() + "访问 menu1";
    }

    @RequestMapping("/r/menu2")
    @PreAuthorize("hasAuthority('menu2')")
    public String menu2() {
        return getUsername() + "访问 menu2";
    }

    @RequestMapping("/m/menu9")
    public String menu9() {
        return getUsername() + "访问 menu9";
    }
}
